// server/api/repositories.get.ts - 分页优化版本
import { defineEventHandler, getQuery } from 'h3'
import { verifyToken } from '../utils/auth'
import prisma from '../utils/prisma'
export default defineEventHandler(async (event) => {
  try {
    // Token验证（保持不变）
    const authHeader = getHeader(event, 'authorization')
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      throw createError({
        statusCode: 401,
        statusMessage: '未提供认证令牌'
      })
    }
    
    const token = authHeader.slice(7)
    const decoded = verifyToken(token)
    if (!decoded) {
      throw createError({
        statusCode: 401,
        statusMessage: '令牌无效或已过期'
      })
    }
    
    // 获取分页参数
    const query = getQuery(event)
    const { 
      username, 
      page = '1',      // 当前页码，默认第一页
      limit = '10'     // 每页数量，默认10条
    } = query
    
    if (!username) {
      throw createError({
        statusCode: 400,
        statusMessage: '需要提供用户名参数'
      })
    }
    
    const pageNum = parseInt(page as string)
    const limitNum = parseInt(limit as string)
    const skip = (pageNum - 1) * limitNum
    
    // 查询用户是否存在
    const user = await prisma.user.findUnique({
      where: { username: username as string }
    })
    
    if (!user) {
      throw createError({
        statusCode: 404,
        statusMessage: '用户不存在'
      })
    }
    
    // 并行查询数据总数和分页数据（性能优化）
    const [repositories, totalCount] = await Promise.all([
      // 分页查询仓库数据
      prisma.repository.findMany({
        where: { userId: user.id },
        skip,
        take: limitNum,
        orderBy: { createdAt: 'desc' }, // 按创建时间倒序
        include: {
          user: {
            select: {
              username: true,
              email: true
            }
          }
        }
      }),
      // 查询总数
      prisma.repository.count({
        where: { userId: user.id }
      })
    ])
    
    // 计算分页信息
    const totalPages = Math.ceil(totalCount / limitNum)
    const hasNextPage = pageNum < totalPages
    const hasPrevPage = pageNum > 1
    
    return {
      code: 200,
      message: '获取成功',
      data: {
        repositories,
        pagination: {
          currentPage: pageNum,
          pageSize: limitNum,
          totalCount,
          totalPages,
          hasNextPage,
          hasPrevPage
        }
      }
    }
    
  } catch (error: any) {
    console.error('分页查询错误:', error)
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || '服务器内部错误'
    })
  }
})